import React, { Component } from 'react';
import PropTypes from 'prop-types'
import { Form, Steps, Button, Row, Col, Modal } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { omit } from 'lodash'
import './steps-form.css'

const nullFnc = () => { }

/**
 *
 * @param {onFinish,stepsProps}
 * @returns {*}
 * @constructor
 */
class StepsForm extends Component {

  state = {
    current: 0,
    loading: false
  }
  forms = {}

  render() {
    const children = React.Children.toArray(this.props.children).filter(Boolean)

    const len = children.length
    const { current, loading } = this.state
    const { onFormChange = nullFnc, onFormFinish = nullFnc, } = this.props
    return (
      <Form.Provider onFormChange={onFormChange} onFormFinish={onFormFinish} >
        <Steps {...this.props.stepsProps} current={current}>
          {React.Children.map(children, (child, index) => {
            return <Steps.Step key={child.props.title} title={child.props.title}>
            </Steps.Step>
          })}
        </Steps>
        <div style={{ borderTop: '1px solid #fff', padding: '0 60px', paddingBottom: 30, }}>
          {React.Children.map(children, (child, index) => {
            return <child.type
              {...child.props} key={index}
              transRef={el => this.forms[child.props.name] = el}
              className={`step-form-container ${current == index ? 'step-form-container-active' : ''}`}
              onFinish={async (values) => {
                this.setState({ loading: true });
                let success
                try {
                  //调step保存接口
                  success = child.props.onFinish ? await child.props.onFinish(values) !== false : true
                } catch (e) {
                  console.log(e)
                }
                this.setState({ loading: false });
                if (success) {
                  if (current < len - 1) {
                    this.setState({ current: current + 1 });
                  } else {
                    //最后一项
                    if (this.props.onFinish) {
                      const allValues = Object.keys(this.forms).reduce((obj, formKey) => {
                        const form = this.forms[formKey]
                        const values = form.getFieldsValue()
                        console.log(666,{values})
                        obj = { ...obj, ...values }
                        return obj
                      }, {})
                      this.props.onFinish(allValues)
                    }
                  }
                }
              }
              }
            ></child.type>
          })}

          <Row justify="center" gutter={24} style={{ marginTop: 30, textAlign: 'center', marginBottom: 20 }}>
            {
              current !== 0 ? <Col>
                <Button
                  loading={loading}
                  type="primary"
                  onClick={() => {
                    if (current > 0) {
                      this.setState({ current: current - 1 });
                    }
                  }}>上一步</Button>
              </Col>
                : <Col>
                  <Button
                    loading={loading}
                    type="primary"
                    onClick={() => {
                      Modal.confirm({
                        okText: '确定',
                        okType: 'danger',
                        cancelText:'取消',
                        cancelButtonProps: { type: 'primary' },
                        title: '确定取消吗？',
                        icon: <ExclamationCircleOutlined />,
                        content: '是否取消创建当前加固任务？',
                        onOk: () => {
                          const form = this.forms[children[current].props.name]
                          form.resetFields()
                          // this.props.navigate('/taskList')

                          let a = document.createElement('a')
                          
                          a.setAttribute('href', '/taskList')
                          a.setAttribute('id', 'nav')
                          document.body.appendChild(a)
                          a.click()
                          document.body.removeChild(document.getElementById('nav'))
                        },
                        onCancel() {
                          console.log('Cancel');
                        },
                      });
                    }}>取消</Button>
                </Col>
            }
            <Col>
              <Button
                loading={loading}
                onClick={() => {
                  const form = this.forms[children[current].props.name]
                  form.validateFields().then(() => {
                    form.submit()
                  }).catch(err => {
                    console.log(err)
                  })

                }} type="primary">{current === len - 1 ? '提交' : '下一步'}</Button>
            </Col>
          </Row>
        </div>
      </Form.Provider>)
  }
}

/**
 *
 * @param {title,name,onFinish}
 * @returns {*}
 * @constructor
 */
class StepForm extends Component {
  onFinish = (values) => {
    if (this.props.onFinish) {
      this.props.onFinish(values)
    }
  }

  render() {
    const formProps = omit(this.props, ['title', 'transRef'])
    return (
      <Form {...formProps} ref={this.props.transRef} onFinish={this.onFinish} >
        {this.props.children}
      </Form>
    )
  }
}
StepForm.propTypes = {
  title: PropTypes.string,
  name: PropTypes.string.isRequired,
  onFinish: PropTypes.func,
}
StepsForm.StepForm = StepForm
export default StepsForm;
